package com.controller.accoun;

import com.entity.Answer;
import com.entity.user.User;
import com.service.account.AccountSerice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {
    @Autowired
    AccountSerice accountSerice;


    @PostMapping("register")
    public Object register(@RequestBody User user){
        return  accountSerice.addUser(user);
    }

    @PostMapping("login")
    public Object login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
        Answer answer = new Answer();
        if (user == null || user.getName() == null || user.getPwd()==null){
            answer.setCode(0);
            answer.setError("参数不可为空！");
            return answer;
        }
        answer = (Answer)accountSerice.login(user);
        if (answer.getData() == null){
            answer.setCode(0);
            answer.setError("账号或密码错误！");
            return answer;
        }
        String token = ((User)answer.getData()).getUserID()+"";
        request.getSession().setAttribute("token",token);
        request.getSession().setAttribute("type",((User) answer.getData()).getType());
        request.getSession().setMaxInactiveInterval(60*60*24);
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        return answer;
    }

}
